<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门店" prop="storeIdArr">
        <el-cascader
          placeholder="请选择门店"
          v-model="queryParams.storeIdArr"
          :options="companyStoreOptions"
          :props="{checkStrictly: true, value: 'id', label: 'name'}"
          clearable
          filterable
          @change="storeArrChange"
          @keyup.enter.native="handleQuery"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="queryParams.role" placeholder="请选择角色" clearable filterable size="small">
          <el-option v-for="r in roleOptions" :value="r.value" :label="r.label" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['store:clerk_user:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['store:clerk_user:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:clerk_user:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['store:clerk_user:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="clerk_userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="门店" align="center" prop="storeId" :formatter="formatterCompanyStore" />
      <el-table-column label="角色" align="center" prop="role">
        <template slot-scope="scope">
          <el-tag
            v-for="it in roleOptions"
            :type="it.type"
            v-if="getRoleByPhone(scope.row) === it.value"
          >{{it.label}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="2"
            @change="statusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:clerk_user:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:clerk_user:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改店员用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="门店" prop="storeId">
          <el-cascader
            placeholder="请选择门店"
            v-model="form.storeId"
            :options="companyStoreOptions"
            :props="{checkStrictly: true, value: 'id', label: 'name'}"
            clearable
          ></el-cascader>
        </el-form-item>
<!--        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="form.role">
            <el-radio v-for="item in roleOptions" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClerk_user, getClerk_user, delClerk_user, addClerk_user, updateClerk_user, exportClerk_user } from "@/api/store/clerk_user";
import {listCompanyStore} from "@/api/store/companyStore";

export default {
  name: "Clerk_user",
  components: {
  },
  data() {
    return {
      companyStoreList: [],
      companyStoreOptions: [],
      roleOptions: [
        {
          label: '店员',
          value: 1,
          type: 'warning'
        },
        {
          label: '店长',
          value: 2,
          type: 'success'
        },
        {
          label: '老板',
          value: 3,
          type: ''
        }
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 店员用户表格数据
      clerk_userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phone: null,
        name: null,
        storeId: null,
        role: null,
        status: null,
        storeIdArr: [],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        storeId: [
          { required: true, message: "门店不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCompanyStoreOptions();
  },
  methods: {
    storeArrChange(e) {
      console.log("当前数据：",e);
      if(e.length === 1) {
        this.queryParams.storeId = "[" + e[0] + ",%]";
      }else {
        this.queryParams.storeId = JSON.stringify(e);
      }
    },
    statusChange(row) {
      updateClerk_user(row).then(res => {
        this.msgSuccess("修改成功");
      })
    },
    getRoleByPhone(row) {
      let res = 1;
      let arr = JSON.parse(row.storeId);
      let len = arr.length;
      this.companyStoreList.forEach(it => {
        if(it.id === Number(arr[len - 1])) {
          if(row.phone === it.userId) {
            if(it.parentId === 0) {
              res = 3
            }else {
              res = 2;
            }
          }
        }
      })
      return res;
    },
    formatterCompanyStore(row) {
      let res = "";
      let arr = JSON.parse(row.storeId);
      arr.forEach(item => {
        this.companyStoreList.forEach(it => {
          if(it.id === Number(item)) {
            res += it.name + " "
          }
        })
      })
      return res;
    },
    getCompanyStoreOptions() {
      listCompanyStore().then(response => {
        this.companyStoreList = response.data;
        this.companyStoreOptions = this.handleTree(response.data, "id", "parentId");
        this.companyStoreOptions.forEach(it => {
          it.children.forEach(item => {
            this.$delete(item, 'children')
          })
        })
      });
    },
    /** 查询店员用户列表 */
    getList() {
      this.loading = true;
      listClerk_user(this.queryParams).then(response => {
        this.clerk_userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createTime: null,
        createBy: null,
        phone: null,
        name: null,
        storeId: null,
        openId: null,
        password: null,
        role: 1
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.storeId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加店员用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getClerk_user(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改店员用户";
        this.form.storeId = JSON.parse(this.form.storeId);
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(this.form.storeId != null) {
        this.form.storeId = JSON.stringify(this.form.storeId)
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClerk_user(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClerk_user(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除店员用户编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delClerk_user(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有店员用户数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportClerk_user(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
